﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;

namespace Nirvana
{
   
    public enum AudioRuleSampleRate
    {
        Hz8000= 8000,
        Hz11025= 11025,
        Hz22050= 22050,
        Hz44100= 44100,
        Hz48000= 48000,
        Hz96000= 96000,
        Hz192000= 192000,
    }

    /// <summary>
    /// 音频资源导入检测规则脚本，根据选定的规则，自动化配置资源参数
    /// 注意：
    ///     规则文件必须存放在资源的父目录或同一级目录下。便于不同资源模块的管理。
    /// </summary>
    [CreateAssetMenu(fileName = "@AudioImportRule", menuName = "Nirvana/Asset/AudioImportRule")]
    public class AudioImportRule : ScriptableObject
    {
        /// <summary>
        /// 指定检测规则的资源
        /// </summary>
        [Tooltip("通过哪些资源.")]
        [SerializeField]
        private ListStringVariate includeRegexs;
        /// <summary>
        /// 忽略规则检测
        /// </summary>
        [Tooltip("排除哪些资源.")]
        [SerializeField]
        private ListStringVariate excludeRegexs;

        [SerializeField]
        [Tooltip("The import rule for 1s audio.")]
        private AudioImportConfig importAudio1;
        [SerializeField]
        [Tooltip("The import rule for 1s~5s audio.")]
        private AudioImportConfig importAudio2;

        [SerializeField]
        [Tooltip("The import rule for more 5s audio.")]
        private AudioImportConfig importAudio5;

        private bool isEnd = true;
        public void SetIsCanProcess(bool flag)
        {
            isEnd = flag;
        }
        /// <summary>
        /// 返回当前配置脚本的存放目录
        /// </summary>
        /// <returns></returns>
        public string GetDirectorName()
        {
            string assetpath = AssetDatabase.GetAssetPath(this);
            return Path.GetDirectoryName(assetpath);
        }

        public static AudioImportRule[] GetAllAssetImportRule()
        {
            string[] allRules = AssetDatabase.FindAssets("t:AudioImportRule");
            List<AudioImportRule> tmps = new List<AudioImportRule>(allRules.Length);
            foreach(var p in allRules)
            {
                string guid = AssetDatabase.GUIDToAssetPath(p);
                tmps.Add(AssetDatabase.LoadAssetAtPath<AudioImportRule>(guid));
            }
            return tmps.ToArray();
        }

        public bool IsMatchRegex(string assetPath)
        {
            if (!isEnd) return false;
            if (!includeRegexs.IsHasValue()) return false;

            string ruleDirname = GetDirectorName();
            ruleDirname = ruleDirname.Replace('/', '\\');
            if (ruleDirname[ruleDirname.Length - 1] != Path.DirectorySeparatorChar) ruleDirname += Path.DirectorySeparatorChar;
           
            string filename = assetPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
            //同一父目录下才检测规则
            if (!filename.StartsWith(ruleDirname, System.StringComparison.OrdinalIgnoreCase)) return false;
            //指定包含的规则
            var temparray = this.includeRegexs.GetValue().ToArray();
            Regex[] regexs = null;
            if(temparray != null && temparray.Length > 0)
            {
                regexs = new Regex[temparray.Length];
                for (int i = 0; i < temparray.Length; i++) regexs[i] = new Regex(temparray[i]);
            }

            //需要忽略的规则
            temparray = this.excludeRegexs.GetValue().ToArray();
            Regex[] exRegexs = null;
            if (temparray != null && temparray.Length > 0)
            {
                exRegexs = new Regex[temparray.Length];
                for (int i = 0; i < temparray.Length; i++)
                    if (!string.IsNullOrEmpty(temparray[i])) exRegexs[i] = new Regex(temparray[i]);

            }

            string input = DirectoryUtil.RelativePath(GetDirectorName(), assetPath);
            if (regexs != null)
            {
                bool flag = false;
                foreach (Regex r in regexs)
                {
                    if (r.IsMatch(input))
                    {
                        flag = true;
                    }
                }
                if (!flag)
                {
                    return false;
                }
            }
            if (exRegexs != null)
            {
                bool flag2 = false;
                foreach (Regex r in exRegexs)
                {
                    if (r.IsMatch(input))
                    {
                        flag2 = true;
                        break;
                    }
                }
                if (flag2)
                {
                    return false;
                }
            }
            return true;
        }

        public void Match1sAudio(AudioImporter audioImporter)
        {
            this.importAudio1.MatchRule(audioImporter);
        }
        public void Match2sAudio(AudioImporter audioImporter)
        {
            this.importAudio2.MatchRule(audioImporter);
        }
        public void Match5sAudio(AudioImporter audioImporter)
        {
            this.importAudio5.MatchRule(audioImporter);
        }
    }
}

